<?php

namespace App\Http\Middleware;

use Closure;

use App\Models\ApiLog;

class ApiService
{

    private $id;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $request_data = $request->all();
        $sign = $request->input('sign');
        $body = $request->input('body');
        $appId = $request->input('appId');
        $api_data = [
           '60000010' => 'ede3256766f611e784a100163e0033b6',
           '6000200' => '7879cc25bac511e7b94d6c92bf482db5', //吴裕泰项目使用
        ];

        $this->addLog($request->path(), $request_data);

        if (empty($appId)) {
           $return_data = ['code' => 100000 , 'message' => '缺少参数：appId'];
           $this->updateLog($return_data);
           return response()->json($return_data);
        }

        if (empty($sign)) {
           $return_data = ['code' => 100000 , 'message' => '缺少参数：sign'];
           $this->updateLog($return_data);
           return response()->json($return_data);
        }

        if (!isset($api_data[$appId])) {
           $return_data = ['code' => 100000 , 'message' => 'appId参数错误'];
           $this->updateLog($return_data);
           return response()->json($return_data);
        }

        //生成签名
        $sign = $this->createSign($request_data, $api_data[$appId]);
        if ($sign != $request_data['sign']) {
           $return_data = ['code' => 100001 , 'message' => '数据加密验签失败，服务器签名：' . $sign];
           $this->updateLog($return_data);
           return response()->json($return_data);
        }

        if ($body) {
           $body_arr = json_decode($body, true);
           if (is_array($body_arr)) {
               foreach ($body_arr as $key => $value) {
                   $request->offsetSet($key, $value);
               }
           }
        }

        $response = $next($request);

        if (method_exists($response, 'getData')) {
            $this->updateLog($response->getData(true));
        } else {
            $this->updateLog('程序执行出错');
        }

        return $response;

    }

    private function createSign($data, $key) {

        ksort($data);

        $sign_str = '';
        foreach ($data as $k => $v) {
            if ($v == '') {
                continue;
            }
            if (in_array($k, ['sign', '_url'])) {
                continue;
            }
            if ($sign_str == '') {
                $sign_str .= $k . '=' . $v;
            } else {
                $sign_str .= '&' . $k . '=' . $v;
            }

        }
        $sign_str .= '&key=' . $key;

        return strtoupper(md5($sign_str));

    }

    /**
     * 添加接口请求数据
     * @param string $api_name 接口名称
     * @param array $request_data 请求数据数组
     * @return mixed
     */
    private function addLog($api_name, $request_data) {

        $log = new ApiLog();
        $log->api_name = $api_name;
        $log->request_data = print_r($request_data, true);
        $log->return_data = null;
        $log->save();

        $this->id = $log->id;

        return true;

    }

    /**
     * 更新接口返回数据
     * @param array $return_data 返回数据数组
     * @return bool
     */
    private function updateLog($return_data) {

        ApiLog::where('id', $this->id)->update(['return_data' => print_r($return_data, true)]);

        return true;

    }

}
